<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>雷达</title>
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta name="viewport"
          content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta name="app-mobile-web-app-capable" content="yes"/>
    <meta name="app-mobile-web-app-status-bar-style" content="black-translucent"/>
    <link rel="stylesheet" href="//at.alicdn.com/t/font_772560_nyw5t78j0pd.css">
    <link rel="stylesheet" href="css/time-detail.css">
    <link rel="stylesheet" href="css/Mdate.css">

</head>
<body>
<div id="app">
    <div class="header">
        <div class="bg-white info_wrap">
            <div class="userInfo flex">
                <div class="avatar">
                    <img id="cus_face"
                         src="https://b-ssl.duitang.com/uploads/item/201204/10/20120410082559_Ztwyf.thumb.700_0.jpeg"
                         alt="">
                </div>
                <div class="flex1">
                    <div class="flex align mt-5">
                        <p id="cus_name" class="name flex1">客户名字</p>
                        <a id="edit" href="./edit-OtherCard.html" class="edit">
                            <i class="ra ra-bianji"></i>
                        </a>
                    </div>
                    <div class="tag_wrap flex align">
                        <ul class="tag_item_wrap" id="tags">
                            <!--<li class="tag_item">我的标签</li>-->
                        </ul>
                        <a href="" class="ra ra-add" id="toTag" style="font-size: 20px;color:#32a4f9;"></a>
                    </div>
                    <p id="cus_phone" class="phone">手机号</p>
                </div>
            </div>
            <div class="flex select">
                <div class="flex1">
                    <p id="except_date" class="title tc"></p>
                    <p class="gray tc">预计成交日期

                    </p>
                    <input id="except_date_value" type="date" class="flex1 tc" value="" placeholder="请输入"
                           onchange="PostValue(2)" style="margin-left: 40px;">
                </div>
                <div class="flex1">
                    <p id="except_rate" class="title tc"></p>
                    <p class="gray tc">预计成交概率

                    </p>
                    <input id="except_rate_value" type="number" class="flex1 tc" value="" placeholder="请输入"
                           onchange="PostValue(1)" style="width: 35px;margin-left: 40px;">%
                </div>
            </div>
        </div>
    </div>
    <div class="flex nav bg-white" id="nav">
        <div class="flex1 tc active"><span>互动跟进</span></div>
        <div id="analysis" class="flex1 tc"><span>客户分析</span></div>
    </div>
    <div class="container" id="nav_item">
        <div class="tab_item time_wrap" id="time_wrap" style="height: 500px;overflow-y: auto;">
            <ul id="cus_action">

            </ul>
        </div>
        <div class="tab_item canvas">
            <div class="chart">
                <p class="chart_title tc">近7天客户兴趣占比</p>
                <canvas id="pie" style="width:345px;height:200px">
                    <p>暂无数据</p>
                </canvas>
            </div>
            <div class="chart">
                <p class="chart_title tc">近7天客户活跃指数</p>
                <canvas id="line" style="width:200px;height:200px">
                </canvas>
            </div>

        </div>
    </div>
    <div style="height:50px"></div>
    <div class="flex bg-white bottom_btn">
        <a id="chatto" href="#" class="flex1 tc">发消息</a>
        <a id="important" href="#" class="flex1 tc">跟进</a>
    </div>

</div>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="js/iScroll.js"></script>
<script src="js/Mdate.js"></script>
<script src='js/echarts.js'></script>

<script>
    function contrastTime(start) {
        var evalue = $('#datePicker').val()
        var dB = new Date(evalue.replace(/-/g, "/"));//获取当前选择日期
        var d = new Date();
        var str = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();//获取当前实际日期
        if (Date.parse(str) > Date.parse(dB)) {//时间戳对比
            return 1;
        }
        return 0;
    }
    //作业开始时间失去焦点验证
    $('#datePicker').blur(function () {
        var ret = contrastTime("startTime");//获取返回值
        if (ret == 1) {
            alert("作业开始时间不能小于当前实际时间。");
            $(this).val('').focus();
            return;
        }
    })


    new Mdate("datePicker", {
        //"dateShowBtn"为你点击触发Mdate的id，必填项
        acceptId: "",
        //此项为你要显示选择后的日期的input，不填写默认为上一行的"dateShowBtn"
        beginYear: "2000",
        //此项为Mdate的初始年份，不填写默认为2000
        beginMonth: "1",
        //此项为Mdate的初始月份，不填写默认为1
        beginDay: "1",
        //此项为Mdate的初始日期，不填写默认为1
        endYear: "",
        //此项为Mdate的结束年份，不填写默认为当年
        endMonth: "12",
        //此项为Mdate的结束月份，不填写默认为当月
        endDay: "31",
        //此项为Mdate的结束日期，不填写默认为当天
        format: "/"
        //此项为Mdate需要显示的格式，可填写"/"或"-"或".",不填写默认为年月日
    })


    //        // 使用刚指定的配置项和数据显示图表。
    //        myChart.setOption(option);
    //        //浏览器大小改变时重置大小
    //        window.onresize = function () {
    //            myChartContainer();
    //            myChart.resize();
    //        };
</script>
<script src="https://cdn.bootcss.com/Chart.js/2.7.2/Chart.min.js"></script>

<script type="text/javascript">


    /**
     * 时间格式转换
     */
    function formatTimeStamp(timestamp, format) {
        if (!timestamp) {
            return 0;
        }
        var formatTime;
        format = format || 'yyyy-MM-dd hh:mm';
        var date = new Date(timestamp * 1000);
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds() //秒
        };
        if (/(y+)/.test(format)) {
            formatTime = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        } else {
            formatTime = format;
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(formatTime))
                formatTime = formatTime.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
        return formatTime;
    }

    /**
     * 地址解码
     */
    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        // var location_url = decodeURI(window.location)
        var r = decodeURI(window.location.search.substr(1)).match(reg);
        if (r != null)return unescape(r[2]);
        return null;
    }


    $(document).ready(function () {
        /**
         * 切换tab
         */
        $('#nav>div').click(function () {
            var index = $(this).index();
            $("#nav_item .tab_item").eq(index).show().siblings().hide();
            $(this).addClass("active").siblings().removeClass("active");
        })
        GetAnalysis(1)
        //初始化
        LoadingDataFn()
    });

    /**
     * 跟进
     */
    $("#important").click(function () {
        var data = {
            'cus_im_id': sessionStorage.getItem('chatwith'),
            'self_im_id': sessionStorage.getItem('login_identifier'),
            'important': sessionStorage.getItem('important'),
        }
        $.ajax({
            url: "https://qyim.ec51.com/v1/check/important-v2", type: "POST", data: data, success: function (result) {
                //console.error(result)
                if (result.data == 0) {
                    alert('操作成功！');
                    $("#important").text('跟进');
                    sessionStorage.setItem('important', result.data)
                } else if (result.data == 1) {
                    alert('操作成功！');
                    $("#important").text('取消跟进');
                    sessionStorage.setItem('important', result.data)
                } else {
                    alert('操作失败')
                }
            }
        });
    });
    /**
     *预计成交率
     */
    function PostValue(type) {
        if (type == 1) {
            var value = $('#except_rate_value').val()
        } else {
            var value = $('#except_date_value').val()
        }
        var data = {
            'cus_im_id': sessionStorage.getItem('chatwith'),
            'self_im_id': sessionStorage.getItem('login_identifier'),
            'value': value,
            'type': type
        }
        console.error(data)
        $.ajax({
            url: "https://qyim.ec51.com/v1/check/change-value-v2", type: "POST", data: data, success: function (result) {
                //console.error(result)
                console.error(result)
            }
        });

    }
    /**
     * 客户跟进情况及客户分析
     */
    $('#analysis').click(function () {
        GetAnalysis(2)
    })
    function GetAnalysis(type) {
        var data = {
            'cus_im_id': GetQueryString('cus_im_id'),
            'self_im_id': sessionStorage.getItem('login_identifier'),
            'face_url': GetQueryString('face_url'),
            'name': GetQueryString('name'),
            'company_id': sessionStorage.getItem('self_store_id'),
            'type': type
        };
        $.ajax({
            url: "https://qyim.ec51.com/v1/check/get-a-cus-info-v2", type: "POST", data: data, success: function (res) {
                //console.error(result)
                var in_my = [];
                var in_other = [];
                var date = [];
                console.log(res)
                $("#cus_face").attr('src', GetQueryString('face_url'))

                if (res.data != false) {
                    if (res.data.type == 1) {
                        $('#toTag').attr("href","tags.html?id="+res.data.customerInfo.id)
                        sessionStorage.setItem('cus_face', res.data.customerInfo.face_url)
                        sessionStorage.setItem('important', res.data.customerInfo.important)
                        $("#cus_phone").html(res.data.customerInfo.phone);
                        $("#except_rate_value").val(res.data.customerInfo.except_rate);
                        $("#except_date_value").val(res.data.customerInfo.except_date);
                        if (res.data.customerInfo.important == 1) {
                            $("#important").text('取消跟进');
                        }
                        var html=''
                        for(var j =0;j<res.data.customerTag.length;j++){
                            html+='<li class="tag_item">'+res.data.customerTag[j].name+'</li>'
                        }
                        $('#tags').append(html)
                    }
                    else {
                        for (var i in res.data.line) {
                            date_day = formatTimeStamp(res.data.line[i].day, 'MM-dd')
                            date.push(date_day);
                            in_other.push(res.data.line[i].in_other)
                            in_my.push(res.data.line[i].in_my)
                        }
                        createLine(date, in_my, in_other)
                        CreatePie(res.data.analysis.card_count, res.data.analysis.shop_count, res.data.analysis.web_count)
                    }
                }
            }
        });
    }
    /**
     * 渲染图
     */
    function CreatePie(a, b, c) {
        var data = {
            labels: [
                "名片兴趣比",
                "商城兴趣比",
                "官网兴趣比"
            ],
            datasets: [
                {
                    data: [a, b, c],
                    backgroundColor: [
                        "#FF6384",
                        "#36A2EB",
                        "#FFCE56"
                    ],
                    hoverBackgroundColor: [
                        "#FF6384",
                        "#36A2EB",
                        "#FFCE56"
                    ]
                }]
        };
        var ctx = document.getElementById("pie").getContext("2d");
        var myBarChart = new Chart(ctx, {
            type: 'pie',
            data: data,
            // options: options
        });
    }
    function createLine(date, my_data, other_data) {
        //数组
        date.reverse()
        my_data.reverse()
        other_data.reverse()
        var ctx = document.getElementById("line").getContext("2d");
        var data = {
            labels: date,
            datasets: [
                {
                    label: "客户总活跃情况",  //当前数据的说明
                    fill: true,  //是否要显示数据部分阴影面积块  false:不显示
                    borderColor: "rgba(200,187,205,1)",//数据曲线颜色
                    pointBackgroundColor: "#fff", //数据点的颜色
                    data: other_data,  //填充的数据
                },
                {
                    label: "客户在我的名片活跃情况",  //当前数据的说明
                    fill: true,  //是否要显示数据部分阴影面积块  false:不显示
                    borderColor: "rgba(75,192,192,1)",//数据曲线颜色
                    pointBackgroundColor: "#fff", //数据点的颜色
                    data: my_data,  //填充的数据
                }
            ]
        }

        var myLineChart = new Chart(ctx, {
            type: 'line',
            data: data,
            scaleLineWidth: 1,
        });

    }


    /**
     * 渲染数据
     */
    var page = 0, //分页码
        // total = 1,//分页总数
        loading = false, //分页开关
        load_flag = true; //分页标识
    var timestamp_today = new Date(new Date().setHours(0, 0, 0, 0)) / 1000 //今天00:00:00的时间戳

    var LoadingDataFn = function () {
        var url = encodeURI("./chat.html?name=" + GetQueryString('name') + "&face=" + GetQueryString('face_url'))
        $('#chatto').attr('href', url)
        var name = GetQueryString('name')
        $("#cus_name").html(name)
        var cus_im_id = GetQueryString('cus_im_id');
        sessionStorage.setItem('chatwith', cus_im_id);
        var data = {
            'cus_im_id': cus_im_id,
            'self_im_id': sessionStorage.getItem('login_identifier'),
            'page': page
        };
        $.ajax({
            url: "https://qyim.ec51.com/v1/check/get-a-customer", type: "POST", data: data, success: function (res) {


                var html = '';
                var list = res.data.cus;

                var time_show = '';
                // var timestamp_today = new Date(new Date().setHours(0,0,0,0)) / 1000 //今天00:00:00的时间戳

                for (var i = 0; i < list.length; i++) {
                    timestamp_action = list[i].time
                    var diff = timestamp_action - timestamp_today
                    // console.error(diff)
                    if (diff <= 86400 && diff >= 0) {
                        time_show = formatTimeStamp(list[i].time, 'hh:mm');
                    } else if (diff < 0 && diff >= -86400) {
                        time_show = '昨天' + formatTimeStamp(list[i].time, 'hh:mm');
                    } else {
                        time_show = formatTimeStamp(list[i].time);
                    }
                    var info = list[i].action_type == 2 ? '查看了你的<span style="color:red"> 名片</span>，建议跟进哦~' : (list[i].action_type == 3 ? '查看了你的<span style="color:red"> 商城</span>，快去和TA联系吧~' : '查看了你的<span style="color:red"> 公司信息 </span>~');
                    if (i == 0) {
                        html += '<li class="time_item"> <div class="date tc"> <span>' + time_show + '</span> </div> <div class="t_content flex">  <div class="avatar"> <img src="' + list[i].cus_face + '" alt=""></div> <p class="t_info flex1">' + '<span style="color:#FF7F00">' + list[i].cus_name + '</span>' + ' ' + info + '</p>  </div>';

                    } else if (i > 0 && list[i - 1].time - list[i].time < 60) {

                        html += '</div> <div class="t_content flex">  <div class="avatar"> <img src="' + list[i].cus_face + '" alt=""></div> <p class="t_info flex1">' + '<span style="color:#FF7F00">' + list[i].cus_name + '</span>' + ' ' + info + '</p>  </div>';

                    } else {
                        html += '</li> <li class="time_item"> <div class="date tc"> <span>' + time_show + '</span> </div> <div class="t_content flex">  <div class="avatar"> <img src="' + list[i].cus_face + '" alt=""></div> <p class="t_info flex1">' + '<span style="color:#FF7F00">' + list[i].cus_name + '</span>' + ' ' + info + '</p>  </div> ';

                    }

                }
                $('#cus_action').append(html);
                // total = res.data.PageCount;
                loading = false;
                // page++;
                if (res.data.flag) {
                    page++;
                } else {
                    load_flag = false;
                }
                $('.loading').remove();
            }
        });

    };


    $('#time_wrap').scroll(function () {
        if (($(this)[0].scrollTop + $(this).height() + 60) >= $(this)[0].scrollHeight) {
            if (loading | !load_flag) {
                return
            }
            loading = true;
            $('#time_wrap').append('<div class="loading"></div>');
            console.log("第" + page + "页");
            LoadingDataFn();
        }
    });

</script>
</body>
</html>